package com.cmdi.feign;

import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSONObject;
import com.cmdi.constant.CodeConstants;
import com.cmdi.domain.JwtToken;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @Description: Feign容错处理类
 * @Author: gaozb
 */
@Configuration
@Slf4j
public class OAuth2FeignClientFallBackFactory implements FallbackFactory<OAuth2FeignClient> {
    @Override
    public OAuth2FeignClient create(Throwable throwable) {
        return new OAuth2FeignClient() {
            @Override
            public ResponseEntity<JwtToken> getToken(String grantType, String username, String password, String loginType, String clientId, String clientSecret, String refreshToken) {
                //会把连接信息显示出来（如password等），需要进行处理
                log.error(CodeConstants.ERROR_REASON_PREFIX, throwable);
                JwtToken jwtToken = new JwtToken();
                jwtToken.setAccessToken("-1");
                if(throwable instanceof FlowException) {
                    jwtToken.setUserInfo(CodeConstants.FLOW_EXCEPTION_PREFIX + throwable.getMessage());
                } else if(throwable instanceof DegradeException) {
                    jwtToken.setUserInfo(CodeConstants.DEGRADE_EXCEPTION_PREFIX + throwable.getMessage());
                } else if(throwable.getCause() instanceof CustomFeignBlockException){
                    //如果throwable是CustomFeignBlockException，那么是cmdi-auth服务调用时返回了异常，那么解析error_description
                    JSONObject parse = JSONObject.parseObject(throwable.getMessage());
                    jwtToken.setUserInfo("登录异常:" + parse.getString("error_description"));
                } else {
                    //throwable.getCause() instanceof ClientException
                    jwtToken.setUserInfo(CodeConstants.OTHER_EXCEPTION_PREFIX + "联系管理员");
                }
                return new ResponseEntity<JwtToken>(jwtToken, HttpStatus.NOT_ACCEPTABLE);
            }
        };
    }
}